﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using XChip_Common;
using XChipTool.Enties;
using System.Configuration;
using BinAnalysisHelp;

namespace XChipTool
{
    public partial class XChip_Lite_Yde : DevExpress.XtraEditors.XtraUserControl
    {

        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        List<string> listfiltration = new List<string> { "slope_i", "scale_sig_i", "scale_all_i" ,  "offset_i" };
        public parameter_exportManager Pe_dal { get; private set; }
        private addressregisterManager aBll;
        private List<addressregister> XChipYde;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        public XChip_Lite_Yde()
        {
            InitializeComponent();
        }
        public XChip_Lite_Yde(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipYde = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "YDE" ));
            InitializeComponent();
        }
        private void XChip_Reg_Yde_Load(object sender, EventArgs e)
        {
            Task.Run(() => {

            this.Invoke((EventHandler)delegate {
            for (int i = 0; i < XChipYde.Count; i++)
            {

                var type = AppHelper.NameTypeToString(XChipYde[i].NameType);
                    //加上单选框的_en
                    if (XChipYde[i].ControlType == "1")
                    {
                        type = XChipYde[i].NameType;
                    }
                    var col = this.Controls.Find(type, true);


                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";
                            if (!string.IsNullOrEmpty(XChipYde[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipYde[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipYde[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipYde[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipYde[i].Bits, XChipYde[i].Bit_Wide, XChipYde.Where(c => c.NameType.ToLower().Contains(type.ToLower()) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
            }
            });
            });


        }
        private long GetYDERegisters(string nameType)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }
            if (XChipYde.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
                return SerialSend.ReadRegister(Convert.ToUInt32(XChipYde.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), sPortTemp);
            else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }

        }
        private long GetYDERegister(string nameType)
        {
            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return -1;
            //}
            //if (XChipYde.Exists(c => c.NameType == nameType))
            //    return SerialSend.ReadRegister(Convert.ToUInt32(XChipYde.Where(c => c.NameType == nameType).First().Address, 16), sPortTemp);
            //else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipYde.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private void SetYDERegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (IsUsbOpen)
            {
               

                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }
                if (isRead) return;

               
                if (null != BinHelp.lspList)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }
            }
            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
        }


        private void scale_sig_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetYDERegister("scale_sig_man_en");
            //SetYDERegister("scale_sig_man_en", (ulong)(scale_sig_man_en.Checked ? (readVal | 0x04) : (readVal & 0xfb)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipYde.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_sig_man_en.Checked ? (readVal | 0x04) : (readVal & 0xfb));
            if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_sig_man_en.Checked);
                SetYDERegister(model, Val);
            }
            EnShowHide();
        }
        private void EnShowHide()
        {
            scale_sig_man.Enabled = scale_sig_man_en.Checked;
            scale_all_man.Enabled = scale_all_man_en.Checked;

            scale_sig0.Enabled = !scale_sig_man_en.Checked;
            scale_sig1.Enabled = !scale_sig_man_en.Checked;
            scale_sig2.Enabled = !scale_sig_man_en.Checked;
            scale_sig3.Enabled = !scale_sig_man_en.Checked;
            scale_sig4.Enabled = !scale_sig_man_en.Checked;
            scale_sig5.Enabled = !scale_sig_man_en.Checked;
            scale_sig6.Enabled = !scale_sig_man_en.Checked;
            scale_sig7.Enabled = !scale_sig_man_en.Checked;
            scale_sig8.Enabled = !scale_sig_man_en.Checked;

            scale_all0.Enabled = !scale_all_man_en.Checked;
            scale_all1.Enabled = !scale_all_man_en.Checked;
            scale_all2.Enabled = !scale_all_man_en.Checked;
            scale_all3.Enabled = !scale_all_man_en.Checked;
            scale_all4.Enabled = !scale_all_man_en.Checked;
            scale_all5.Enabled = !scale_all_man_en.Checked;
            scale_all6.Enabled = !scale_all_man_en.Checked;
            scale_all7.Enabled = !scale_all_man_en.Checked;
            scale_all8.Enabled = !scale_all_man_en.Checked;
        }
        private void scale_all_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetYDERegister("scale_all_man_en");
            //SetYDERegister("scale_all_man_en", (ulong)(scale_all_man_en.Checked ? (readVal | 0x08) : (readVal & 0xf7)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipYde.Find(c => c.NameType.ToLower() == $"scale_all_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_all_man_en.Checked ? (readVal | 0x08) : (readVal & 0xf7));
            if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_all_man_en".ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_all_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_all_man_en.Checked);
                SetYDERegister(model, Val);
            }
            EnShowHide();
        }

        private void slope_k_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_k.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(slope_k.Text, 16);
            //    //SetYDERegister("slope_k", (ulong)nHigh);
            //    if (XChipYde.Exists(c => c.NameType.ToLower() == $"slope_k".ToLower()))
            //    {
            //        var model = XChipYde.Find(c => c.NameType.ToLower() == $"slope_k".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_k.Text);
            //        SetYDERegister(model, Val);
            //    }
            //}
        }

        private void slope_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_k_KeyDown(sender, keyEnter);
        }

        private void slope_b_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_b.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(slope_b.Text, 16);
            //    //SetYDERegister("slope_b", (ulong)nHigh);
            //    if (XChipYde.Exists(c => c.NameType.ToLower() == $"slope_b".ToLower()))
            //    {
            //        var model = XChipYde.Find(c => c.NameType.ToLower() == $"slope_b".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_b.Text);
            //        SetYDERegister(model, Val);
            //    }
            //}
        }

        private void slope_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_b_KeyDown(sender, keyEnter);
        }

        private void offset_k_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_k.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(offset_k.Text, 16);
            //    //SetYDERegister("offset_k", (ulong)nHigh);
            //    if (XChipYde.Exists(c => c.NameType.ToLower() == $"offset_k".ToLower()))
            //    {
            //        var model = XChipYde.Find(c => c.NameType.ToLower() == $"offset_k".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_k.Text);
            //        SetYDERegister(model, Val);
            //    }
            //}
        }

        private void offset_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_k_KeyDown(sender, keyEnter);
        }

        private void offset_b_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_b.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(offset_b.Text, 16);
            //    //SetYDERegister("offset_b", (ulong)nHigh);
            //    if (XChipYde.Exists(c => c.NameType.ToLower() == $"offset_b".ToLower()))
            //    {
            //        var model = XChipYde.Find(c => c.NameType.ToLower() == $"offset_b".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_b.Text);
            //        SetYDERegister(model, Val);
            //    }
            //}
        }

        private void offset_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_b_KeyDown(sender, keyEnter);
        }

        private void scale_sig0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetYDERegister($"scale_sig{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }

        }

        private void scale_sig0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig0_KeyDown(sender, keyEnter);
        }

        private void scale_all0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
        }

        private void scale_all0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_all0_KeyDown(sender, keyEnter);
        }

        private void scale_enh_actv0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }

        }

        private void scale_enh_actv0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_actv0_KeyDown(sender, keyEnter);
        }

        private void scale_sig_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sig_man.Text))
            {
              
                if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_sig_man".ToLower()))
                {
                    var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_sig_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sig_man.Text);
                    SetYDERegister(model, Val);
                }
            }
        }

        private void scale_sig_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig_man_KeyDown(sender, keyEnter);
        }

        private void scale_all_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_all_man.Text))
            {
                
                if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_all_man".ToLower()))
                {
                    var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_all_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_all_man.Text);
                    SetYDERegister(model, Val);
                }
            }
        }

        private void scale_all_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_all_man_KeyDown(sender, keyEnter);
        }

        private void scale_pos_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_pos.Text))
            {
                
                if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_pos".ToLower()))
                {
                    var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_pos".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_pos.Text);
                    SetYDERegister(model, Val);
                }
            }
        }

        private void scale_pos_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_pos_KeyDown(sender, keyEnter);
        }

        private void scale_neg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_neg.Text))
            {
                
                if (XChipYde.Exists(c => c.NameType.ToLower() == $"scale_neg".ToLower()))
                {
                    var model = XChipYde.Find(c => c.NameType.ToLower() == $"scale_neg".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_neg.Text);
                    SetYDERegister(model, Val);
                }
            }
        }

        private void scale_neg_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_neg_KeyDown(sender, keyEnter);
        }

        private void sth_var_ratio_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(sth_var_ratio.Text))
            //{
                 
            //    if (XChipYde.Exists(c => c.NameType.ToLower() == $"sth_var_ratio".ToLower()))
            //    {
            //        var model = XChipYde.Find(c => c.NameType.ToLower() == $"sth_var_ratio".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, sth_var_ratio.Text);
            //        SetYDERegister(model, Val);
            //    }
            //}
        }

        private void sth_var_ratio_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            sth_var_ratio_KeyDown(sender, keyEnter);
        }

       

       

     
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
            List<string> NameList = new List<string>();
            string nameType = string.Empty;
            
            for (int i = 0; i < XChipYde.Count; i++)
            {

                var type = AppHelper.NameTypeToString(XChipYde[i].NameType);
                
                //加上单选框的_en
                if (XChipYde[i].ControlType == "1")
                {
                    type = XChipYde[i].NameType;
                }
                if (type.Contains("scale_sig_man"))
                {

                }
                try
                {
                    var col = this.Controls.Find(type, true);
                    foreach (var item in col)
                    {
                        //过滤掉指定寄存器
                        if (listfiltration.Exists(c => c == item.Name.ToString()))
                        {
                            continue;
                        }
                        if (NameList.Exists(c => c==(type)))
                        {
                            continue;
                        }
                        else {
                            
                            if (item is TextEdit)
                            {
                                var nList = XChipYde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count == 1)
                                {
                                    var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                    item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                                }
                                else
                                {
                                    string Val = string.Empty;
                                    //这里默认为是有多个寄存器  一个文本框的情况进行处理
                                    if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                                    }
                                    if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m3")).Address, 16), sPortTemp).ToString("X2");
                                    }
                                    if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                    }
                                    item.Text = Val;
                                }
                            }
                            else if (item  is CheckEdit)
                            {
                                var nList = XChipYde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                                if (nList.Count ==1)
                                {
                                    var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                    (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val)==0;
                                }
                            }

                          
                        }
                    }
                    NameList.Add(type);
                    //if (nameType == type) continue;
                    //nameType = type;

                    //if (col is TextEdit)
                    //{
                    //    //过滤掉指定寄存器
                    //    if (listfiltration.Exists(c => c == col.Name.ToString()))
                    //    {
                    //        continue;
                    //    }
                    //    var nameList = XChipYde.Where(c => c.NameType.Contains(type)).ToList();

                    //    long tempU = 0;
                    //    foreach (var nitem in nameList)
                    //    {
                    //        tempU += GetYDERegister(nitem.NameType);
                    //    }
                    //    col.Text = tempU.ToString("X");
                    //}
                    //else if (col is CheckEdit)
                    //{
                    //    (col as CheckEdit).Checked = (GetYDERegister(type) == 0);
                    //}
                }
                catch (Exception)
                {
                    continue;
                }
            }
            //y_slope0.Text = (GetYDERegisters("y_slope0_h").ToString("X") + GetYDERegisters("y_slope0_l").ToString("X2"));
            //y_slope1.Text = (GetYDERegisters("y_slope1_h").ToString("X") + GetYDERegisters("y_slope1_l").ToString("X2"));
            isRead = false;
            WaitBefore.Close();
             
        }


        public void Get_SlopeOffsetSigmaNr()
        {
            //slope_i.Text = GetYDERegister("slope_i").ToString("X2");
            //offset_i.Text = (GetYDERegister("offset_i_h")+ GetYDERegister("offset_i_l")).ToString("X4");
            //scale_sig_i.Text = GetYDERegister("scale_sig_i").ToString("X2");
            //scale_all_i.Text = GetYDERegister("scale_all_i").ToString("X2");

        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            Get_SlopeOffsetSigmaNr();
        }
        private void x_node0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void x_node0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            x_node0_KeyDown(sender, keyEnter);
        }
        private void x_node1_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //x_node[1] - x_node[0] >= 16
            var x_no1 = Convert.ToInt32(txtEdit.Text, 16);
            //if (string.IsNullOrEmpty(x_node0.Text)) return;
            //var x_no0 = Convert.ToInt32(x_node0.Text, 16);
            //if (x_no1 - x_no0 <16)
            //{
            //    ToolTip tip = new ToolTip();
            //    {
            //        var msg = "正确填写：x_node[1] - x_node[0] >= 16";
            //        tip.IsBalloon = true;
            //        tip.SetToolTip(txtEdit, msg);
            //        tip.Show(msg, txtEdit, 3 * 1000);
            //    }
            //    return;
            //}
            //SetYDERegister($"x_node{txtEdit.Tag.ToString()}", (ulong)x_no1);
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void x_node1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            x_node1_KeyDown(sender, keyEnter);
        }

        private void x_node2_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var x_no2 = Convert.ToInt32(txtEdit.Text, 16);
            //x_node[2] - x_node[1] >= 0
            //if (string.IsNullOrEmpty(x_node1.Text)) return;
            //var x_no1 = Convert.ToInt32(x_node1.Text, 16);
            //if (x_no2 - x_no1 < 0)
            //{
            //    ToolTip tip = new ToolTip();
            //    {
            //        var msg = "正确填写：x_node[2] - x_node[1] >= 0";
            //        tip.IsBalloon = true;
            //        tip.SetToolTip(txtEdit, msg);
            //        tip.Show(msg, txtEdit, 3 * 1000);
            //    }
            //    return;
            //}
            //SetYDERegister($"x_node{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void x_node2_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            x_node2_KeyDown(sender, keyEnter);
        }

        private void x_node3_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var x_no3 = Convert.ToInt32(txtEdit.Text, 16);
            //if (string.IsNullOrEmpty(x_node2.Text)) return;
            //var x_no2 = Convert.ToInt32(x_node2.Text, 16);
            ////x_node[3] - x_node[2] >= 16
            //if (x_no3 - x_no2 < 16)
            //{
            //    ToolTip tip = new ToolTip();
            //    {
            //        var msg = "正确填写：x_node[3] - x_node[2] >= 16";
            //        tip.IsBalloon = true;
            //        tip.SetToolTip(txtEdit, msg);
            //        tip.Show(msg, txtEdit, 3 * 1000);
            //    }
            //    return;
            //}
            //SetYDERegister($"x_node{txtEdit.Tag.ToString()}", (ulong)x_no3);
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void x_node3_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            x_node3_KeyDown(sender, keyEnter);
        }
        private void y_node0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetYDERegister($"y_node{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void y_node0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            y_node0_KeyDown(sender, keyEnter);
        }
        private void y_node1_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var y_no1 = Convert.ToInt32(txtEdit.Text, 16);
            //y_node[1] >= y_node[0]
            //if (string.IsNullOrEmpty(y_node0.Text)) return;
            //var y_no0 = Convert.ToInt32(y_node0.Text, 16);
            //if (y_no1 < y_no0)
            //{
            //    ToolTip tip = new ToolTip();
            //    {
            //        var msg = "正确填写：y_node[1] >= y_node[0]";
            //        tip.IsBalloon = true;
            //        tip.SetToolTip(txtEdit, msg);
            //        tip.Show(msg, txtEdit, 3 * 1000);
            //    }
            //    return;
            //}
            //SetYDERegister($"y_node{txtEdit.Tag.ToString()}", (ulong)y_no1);
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }

        private void y_node1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            y_node1_KeyDown(sender, keyEnter);
        }

        private void y_node2_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var y_no2 = Convert.ToInt32(txtEdit.Text, 16);
            //if (string.IsNullOrEmpty(y_node1.Text)) return;
            //var y_no1 = Convert.ToInt32(y_node1.Text, 16);
            ////y_node[1] >= y_node[2]
            //if (y_no1 < y_no2)
            //{
            //    ToolTip tip = new ToolTip();
            //    {
            //        var msg = "正确填写：y_node[1] >= y_node[2]";
            //        tip.IsBalloon = true;
            //        tip.SetToolTip(txtEdit, msg);
            //        tip.Show(msg, txtEdit, 3 * 1000);
            //    }
            //    return;
            //}
            //SetYDERegister($"y_node{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }
            Set_y_slope0();
            Set_y_slope1();
        }


        private void Set_y_slope0() {
            //y_slope[0] = (y_node[1] - y_node[0]) * 256 / (x_node[1] - x_node[0])
            //if (string.IsNullOrEmpty(y_node1.Text)) return;
            //if (string.IsNullOrEmpty(y_node0.Text)) return;

            //if (string.IsNullOrEmpty(x_node1.Text)) return;
            //if (string.IsNullOrEmpty(x_node0.Text)) return;

            //y_slope0.Text = (((Convert.ToInt32(y_node1.Text, 16) - Convert.ToInt32(y_node0.Text, 16)) * 256)
            //    / (Convert.ToInt32(x_node1.Text, 16) - Convert.ToInt32(x_node0.Text, 16))).ToString("X2");
        }

        private void Set_y_slope1() {
            //y_slope[1] = (y_node[1] - y_node[2]) * 256 / (x_node[3] - x_node[2])
            //if (string.IsNullOrEmpty(y_node1.Text)) return;
            //if (string.IsNullOrEmpty(y_node2.Text)) return;

            //if (string.IsNullOrEmpty(x_node3.Text)) return;
            //if (string.IsNullOrEmpty(x_node2.Text)) return;
            //y_slope1.Text = (((Convert.ToInt32(y_node1.Text, 16) - Convert.ToInt32(y_node2.Text, 16)) * 256)
            //  / (Convert.ToInt32(x_node3.Text, 16) - Convert.ToInt32(x_node2.Text, 16))).ToString("X2");
        }
        private void y_node2_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            y_node2_KeyDown(sender, keyEnter);

        }
        private void y_slope0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //y_slope[0] = (y_node[1] - y_node[0]) * 256 / (x_node[1] - x_node[0])
            //SetYDERegister($"y_slope{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }

        }

        private void y_slope0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            y_slope0_KeyDown(sender, keyEnter);
        }
        private void y_slope1_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //y_slope[1] = (y_node[1] - y_node[2]) * 256 / (x_node[3] - x_node[2])
            //SetYDERegister($"y_slope{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipYde.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYde.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYDERegister(model, Val);
            }

        }
        private void y_slope1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            y_slope1_KeyDown(sender, keyEnter);
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_YDE_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SerialSend.isDebug = false;
                StringBuilder sb = new StringBuilder();
                Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetList(c => c.Module == "YDE").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    //var Pe_patch_dal = new parameter_export_patchManager();
                    //var patchList = Pe_patch_dal.GetList();
                    //var conditionList = tempList.Select(c => c.ConditionAddr).Distinct().ToList();
                    //foreach (var item in conditionList)
                    //{
                    //    if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                    //    {
                    //        patchList.RemoveAll(c => c.ConditionAddr == item);
                    //    }
                    //}
                    #endregion
                    sb.Append("0xffff,0xfef1,\n");
                    sb.Append("\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 判断是否需要用白天的数据
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                
                                 sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                               
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            //setShowMsg(item.RelationAddr);
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
            }
            SerialSend.isDebug = true;
        }

        private void yde_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            
            //if (XChipYde.Exists(c => c.NameType.ToLower() == $"yde_en".ToLower()))
            //{
            //    var model = XChipYde.Find(c => c.NameType.ToLower() == $"yde_en".ToLower());
            //    var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
            //    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), yde_en.Checked);
            //    SetYDERegister(model, Val);
            //}
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //if (XChipYde.Exists(c => c.NameType.ToLower() == $"y_slope0_h".ToLower()))
            //{
            //    var model = XChipYde.Find(c => c.NameType.ToLower() == $"y_slope0_h".ToLower());
            //    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, y_slope0.Text);
            //    SetYDERegister(model, Val);
            //}
            //if (XChipYde.Exists(c => c.NameType.ToLower() == $"y_slope0_l".ToLower()))
            //{
            //    var model = XChipYde.Find(c => c.NameType.ToLower() == $"y_slope0_l".ToLower());
            //    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, y_slope0.Text);
            //    SetYDERegister(model, Val);
            //}
            //if (XChipYde.Exists(c => c.NameType.ToLower() == $"y_slope1_h".ToLower()))
            //{
            //    var model = XChipYde.Find(c => c.NameType.ToLower() == $"y_slope1_h".ToLower());
            //    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, y_slope1.Text);
            //    SetYDERegister(model, Val);
            //}
            //if (XChipYde.Exists(c => c.NameType.ToLower() == $"y_slope1_l".ToLower()))
            //{
            //    var model = XChipYde.Find(c => c.NameType.ToLower() == $"y_slope1_l".ToLower());
            //    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, y_slope1.Text);
            //    SetYDERegister(model, Val);
            //}

        }
    }
}
